package com.liz.lizrpccore.templates;

import com.liz.lizrpccore.properties.MyRedisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

/**
 * @author liangGongWei
 * @description
 * @create 2021-08-05 21:38
 **/
public class MyRedisTemplate {

    //    @Autowired
    private MyRedisProperties redisProperties;

    public MyRedisTemplate(MyRedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }


    public Jedis getJedis() {
        Jedis jedis = new Jedis(redisProperties.getHost(), 6379);
        jedis.auth(redisProperties.getPassword());
        return jedis;
    }

    public void closeJedis(Jedis jedis) {
        jedis.close();
    }


    public String setString(String key, String val) {
        Jedis jedis = this.getJedis();
        String set = jedis.set(key, val);
        this.closeJedis(jedis);
        return set;
    }


    public boolean existsElement(String key) {
        Jedis jedis = this.getJedis();
        Boolean exists = jedis.exists(key);
        if (exists) {
            Long length = this.getJedis().llen(key);
            exists = length.intValue() > 0;
        }
        this.closeJedis(jedis);
        return exists;
    }

    public String getAndRemoveFromList(String key) {
        Jedis jedis = this.getJedis();
        String lpop = jedis.lpop(key);
        this.closeJedis(jedis);
        return lpop;
    }


    public boolean rPush(String key, String val) {
        Jedis jedis = this.getJedis();
        Long resCount = jedis.rpush(key, val);
        boolean res = resCount.intValue() > 0;
        this.closeJedis(jedis);
        return res;
    }

    public String getStr(String key) {
        Jedis jedis = this.getJedis();
        String res = jedis.get(key);
        this.closeJedis(jedis);
        return res;
    }


    public void delKey(String key) {
        Jedis jedis = this.getJedis();
        jedis.del(key);
        this.closeJedis(jedis);
    }


}
